import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable }     from 'rxjs/Observable';

import {Article} from '../entity/article';
import {ArticleArea} from "../entity/articleArea";

@Injectable()
export class ArticleService {

    private httpUrl = 'http://localhost:8080';

    constructor (private http: Http) {}

    private extractData(res: Response) {
        let body = res.json();
        return body.data.data || { };
    }

    private handleError (error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }

    getArticles(page:number,aaid:string):Observable<Article[]> {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.httpUrl+"/getArticles", { page, aaid }, options)
            .map(this.extractData)
            .catch(this.handleError);
    }

    insertArticle(aaid:string,title:string,uploader:string,synopsis:string,content:string):void {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        this.http.post(this.httpUrl+"/insertArticle", { aaid,title,uploader,synopsis,content }, options).toPromise()
            .then(this.extractData)
            .catch(this.handleError);

    }

    getArticlesAreas():Observable<ArticleArea[]> {
        return this.http.get(this.httpUrl+"/getArticleAreas")
            .map(this.extractData)
            .catch(this.handleError);
    }

    getArticle(id:string):Promise<Article> {

        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.httpUrl+"/getArticle", { id }, options)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }
}